'use client'

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { useState } from 'react'

export function QueryProvider({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            // 数据缓存时间 5 分钟
            staleTime: 5 * 60 * 1000,
            // 缓存保持时间 10 分钟
            gcTime: 10 * 60 * 1000,
            // 失败重试次数
            retry: 1,
            // 窗口聚焦时重新获取数据
            refetchOnWindowFocus: false,
            // 网络重连时重新获取数据
            refetchOnReconnect: true,
          },
        },
      })
  )

  return (
    <QueryClientProvider client={queryClient}>
      {children}
      {process.env.NODE_ENV === 'development' && <ReactQueryDevtools />}
    </QueryClientProvider>
  )
}
